<template>
  <van-icon
    :color="isLiked === 1 ? '#ff6666' : '#777'"
    :name="isLiked === 1 ? 'good-job' : 'good-job-o -o'"
    @click="onLike"
  />
</template>

<script>
import { addLike, deleteLike } from '@/api/article'

import { debounce } from 'loadsh'

export default {
  name: 'LikeArticle',
  model: {
    prop: 'isLiked',
    event: 'update-articleLike'
  },
  props: {
    isLiked: {
      type: Number,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  methods: {
    onLike: debounce(async function() {
      try {
        let status = -1
        if (this.isLiked === 1) {
          // 已点赞 取消点赞
          await deleteLike(this.articleId)
          this.$toast.success('取消成功')
        } else {
          // 未点赞 添加点赞
          await addLike(this.articleId)
          this.$toast.success('点赞成功')
          status = 1
        }

        // 更新视图
        this.$emit('update-articleLike', status)
      } catch (error) {
        this.$toast.fail('操作失败,请稍后重试!')
      }
    }, 200)
  }
}
</script>

<style lang="less" scoped></style>
